#!/usr/bin/env bash
# Copyright (c) 2023-2024 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0

CUR_DIR=$(pwd)
WORK_DIR="$CUR_DIR/repo_$(date +%Y%m%d)"
TMP_DIR="$WORK_DIR/tmp"
YUM_DIR="$TMP_DIR/yum"
YUM_CONFIG_FILE="$YUM_DIR/yum.conf"

OBS_PROJECT=""
OBS_REPO_URL="http://10.30.33.235:82"

usage() {
printf "create publish repo from obs repo

usage:
    bash obs_createrepo.sh [-h] [-p PROJECT] [-u URL] [-d DIR]

optional arguments:
    -p PROJECT     obs project name
    -u URL         url of obs repo, default is %s
    -d DIR         directory of publish repo, default is repo_yyyymmdd
    -h             show the help message and exit
\n" "$OBS_REPO_URL"
}

parse_cmdline() {
    while getopts ":p:u:d:h" opt; do
        case "$opt" in
            p)
                OBS_PROJECT="$OPTARG"
            ;;
            u)
                OBS_REPO_URL="$OPTARG"
            ;;
            d)
                local dir=$(realpath "$OPTARG")
                if [ ! -d "$dir" ]; then
                    echo "$OPTARG: no such directory"
                    exit 1
                fi
                WORK_DIR=$dir
                TMP_DIR=$WORK_DIR/tmp
            ;;
            h)
                usage; exit 0
            ;;
            ?)
                echo "please check the params."; usage; return 1
            ;;
        esac
    done
    if [ -z "$OBS_PROJECT" ]; then
        echo "invalid PROJECT arguments"; return 1
    fi
    return 0
}

check_requires() {
    local ret=0

    for c in createrepo dnf; do
        command -v $c > /dev/null
        if [ $? -ne 0 ]; then
            echo "command $c not found"
            ret=1
        fi
    done

    return $ret
}

# create_yum_repo YUM_DIR YUM_CONFIG_FILE REPOS
create_yum_repo() {
    local yum_dir="$1"
    local yum_config_file="$2"
    local repos="$3"
    local yum_repo_dir="${yum_dir}/yum.repos.d"
    local yum_repo_file="${yum_repo_dir}/os.repo"

    mkdir -p "$yum_repo_dir"

    cat > "${yum_config_file}" <<EOF
[main]
gpgcheck=1
installonly_limit=3
clean_requirements_on_remove=True
best=True
skip_if_unavailable=False
reposdir=${yum_repo_dir}
EOF

    local project_url=${OBS_PROJECT//:/:/}  # tr : to :/
    for repo_name in $repos; do
        local repo_url="$OBS_REPO_URL/$project_url/$repo_name"
        cat >> "${yum_repo_file}" <<EOF
[$repo_name]
name=$repo_name
baseurl=$repo_url
enabled=1
gpgcheck=0

EOF
    done
}

do_main() {
    cd "$CUR_DIR" || exit
    [[ -d "${WORK_DIR}" ]] && rm -rf "${WORK_DIR}"

    mkdir -p "$YUM_DIR"
    create_yum_repo "$YUM_DIR" "$YUM_CONFIG_FILE" "standard_x86_64 standard_aarch64"

    # create repo directory tree
    local repo_dirs="aarch64 x86_64 source"
    for d in $repo_dirs; do
        mkdir -p $WORK_DIR/$d/Packages
    done

    # download rpms
    mkdir -p $TMP_DIR
    for arch in aarch64 x86_64; do
        local destdir="${WORK_DIR}/$arch/Packages"
        local rpm_file="$TMP_DIR/rpm_${arch}.txt"
        local rpm_bin_file="$TMP_DIR/rpm_bin_${arch}.txt"
        local rpm_src_file="$TMP_DIR/rpm_src_${arch}.txt"
        yum list -c "$YUM_CONFIG_FILE" --available --repo standard_${arch} | awk '{print $1}' > "$rpm_file"
        grep -E "\.(noarch|$arch)$" "$rpm_file" > "$rpm_bin_file"
        yumdownloader -c "$YUM_CONFIG_FILE" --repo standard_${arch} --destdir="${destdir}" $(tr '\n' ' ' < "$rpm_bin_file")
        if [ $? -ne 0 ] || [ $(ls ${destdir} | wc -l) -eq 0 ]; then
           echo "Download rpms from standard_${arch} failed!"
           return 1
        fi
        grep -E "\.src$" "$rpm_file" > "$rpm_src_file"
    done
    local srcdir="${WORK_DIR}/source/Packages"
    local rpm_src_x86_64_file="$TMP_DIR/rpm_src_x86_64.txt"
    local rpm_src_aarch64_file="$TMP_DIR/rpm_src_aarch64.txt"
    local rpm_src_diff_file="$TMP_DIR/rpm_src_diff.txt"
    sort "$rpm_src_aarch64_file" "$rpm_src_x86_64_file" "$rpm_src_x86_64_file" | uniq -u > "$rpm_src_diff_file"
    if [ -s "$rpm_src_x86_64_file" ]; then
        yumdownloader -c "$YUM_CONFIG_FILE" --repo standard_x86_64 --destdir="${srcdir}" --source $(tr '\n' ' ' < "$rpm_src_x86_64_file")
        if [ $? -ne 0 ] || [ $(ls ${srcdir} | wc -l) -eq 0 ]; then
           echo "Download source rpms from standard_x86_64 failed!"
           return 1
        fi
    fi
    if [ -s "$rpm_src_diff_file" ]; then
        yumdownloader -c "$YUM_CONFIG_FILE" --repo standard_aarch64 --destdir="${srcdir}" --source $(tr '\n' ' ' < "$rpm_src_diff_file")
        if [ $? -ne 0 ] || [ $(ls ${srcdir} | wc -l) -eq 0 ]; then
           echo "Download source rpms from standard_aarch64 failed!"
           return 1
        fi
    fi

    # make repo
    for d in $repo_dirs; do
        createrepo "$WORK_DIR/$d"
    done

    [[ -d "${TMP_DIR}" ]] && rm -rf "${TMP_DIR}"
    return 0
}

main() {
    parse_cmdline "$@"
    if [ $? -ne 0 ]; then
        echo "parse params failed, try -h for help"
        return 1
    fi

    check_requires
    if [ $? -ne 0 ]; then
        echo "check requires failed"
        return 1
    fi

    do_main
    if [ $? -ne 0 ]; then
        return 1
    fi

    return 0
}

main "$@"
